from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.conf import settings
import httpx
from datetime import datetime
import os
from django.views import View
from django.views.decorators.http import require_http_methods

from .models import UserInfo


# Create user views here.


def home(request):
    # 采集文旅信息
    spider = CollectCultureInfo()
    recommend = spider.run()
    # 验证用户身份
    username = request.COOKIES.get('username')
    user = UserInfo.objects.get(name=username)
    # print(recommend)
    context = {
        'user': user,
        'recommend': recommend[:6]
    }
    return render(request, "index.html", context=context)


class LoginView(View):

    def get(self, request):

        return render(request, "user/signin.html")

    def post(self, request):

        try:
            # 获取Post请求得到用户名和密码
            username = request.POST['username']
            password = request.POST['password']
            user = UserInfo.objects.get(name=username)
            print(username, password)

            # 用render生成一个response对象
            if user.name == username and user.password == password:
                response = redirect('user:index')
                # 保存用户登录状态标志位在cookie里面
                response.set_cookie("user_status", "is_login")
                response.set_cookie("username", username)
                # 将登陆用户的ID和姓名存入session
                request.session['user_id'] = user.id
                request.session['user_name'] = user.name
                return response
            else:
                response = render(request, "user/signin.html", context={"message": "ERROR：账号密码错误！"})
                return response
        except Exception as e:
            print(e)
            return render(request, "user/signin.html", context={"message": "ERROR：账号密码错误！"})


class RegisterView(View):

    def get(self, request):
        """用户get请求渲染注册页面"""
        return render(request, 'user/signup.html')

    def post(self, request):
        """用户post请求创建账号"""
        try:
            # 获取来自register.html模板的表单数据
            username = request.POST.get('username')
            signup_password = request.POST.get('signup-password')
            confirm_password = request.POST.get('confirm-password')
            # 判断用户是否存在
            user = UserInfo.objects.filter(name=username)
            if user:
                return render(request, 'user/signup.html', context={'message': 'ERROR：用户已存在！'})
            # 判断两次密码是否一致
            if signup_password != confirm_password:
                return render(request, 'user/signup.html', context={'message': 'ERROR：两次输入密码不一致！'})
            # encrypt_pwd = make_password(password)
            # 创建一个新用户
            UserInfo.objects.create(name=username, password=signup_password)
            print(username, signup_password)
            return render(request, "user/signin.html")  # 注册成功
        except Exception as e:
            print(e)
            return render(request, 'user/signup.html', context={'message': 'ERROR：服务器异常！'})  # 注册失败


@require_http_methods('GET')
def user_logout(request):
    """用户退出登陆"""
    response = redirect('user:signin')
    response.delete_cookie('user_status')
    response.delete_cookie('username')

    return response


class CollectCultureInfo:

    def __init__(self):
        self.url = "https://weibo.com/ajax/statuses/mymblog?uid=2031569683&page=1"
        self.directory = os.path.join(settings.STATICFILES_DIRS[0], 'picture\\recommend')
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
            "Referer": "https://weibo.com"
        }
        self.cookies = {
            "SINAGLOBAL": "1841074107512.084.1588840469173",
            "SCF": "Aka_eNvclJdZgkVwd7SGgIqFfOITZ7i0JuePJPe6RVbO2qaSBfh4sekjwOszJZG2cVQzIii-O2jiEbWyCBhjlzY.",
            "UOR": ",,www.baidu.com",
            "XSRF-TOKEN": "tB3y4HVx1OCtVUXA8BPVXYyf",
            "ALF": "1711248118",
            "SUB": "_2A25I3HWnDeRhGeNM6FQV8inJyTiIHXVrkPdvrDV8PUJbkNAGLULXkW1NTjM0TXSQGgIyzqsHffLj-H4r-uU4_koz",
            "SUBP": "0033WrSXqPxfM725Ws9jqgMF55529P9D9WWTzTuhPe1EuL_gCS91a6On5JpX5KMhUgL.Fo-Ee0qXeoMfeoB2dJLoIp-LxK-LBo5L12q7Uo5LxK-L1K2L1hqt",
            "_s_tentry": "weibo.com",
            "Apache": "5644763397929.464.1708656146562",
            "ULV": "1708656146638:32:2:1:5644763397929.464.1708656146562:1707666667195",
            "WBPSESS": "TnSyL_Lt2vm-x5WYYkobCxMZSiOwteZ8a27WeBLP2hGkXUZtVqgpOLz1yFQ7Q4L2qZsgZBPStAb9OjtPVJ4Ct39bBWA8yuzMdw2cGfUEkLOSaP8S-M6yD6BG3EoQ9NZwsCQ85NNMtNuLZBpBJC02Tw=="
        }
        self.json_data = {}
        self.client = httpx.Client(http2=True, verify=False)

    def get_json(self):
        try:
            resp = self.client.get(url=self.url, headers=self.headers, cookies=self.cookies, timeout=5)
            self.json_data = resp.json()
        except:
            pass

    def parse_json(self):
        fmt_in = "%a %b %d %H:%M:%S %z %Y"
        fmt_out = "%Y-%m-%d %H:%M:%S"
        fmt_name = "%Y-%m-%d-%H%M%S"
        context = []
        for item in self.json_data['data']['list']:
            # 发布的时间
            created_at = item['created_at']
            dt = datetime.strptime(created_at, fmt_in)
            formatted_time = dt.strftime(fmt_out)
            formatted_name = dt.strftime(fmt_name)
            # 发布的内容
            text_raw = item.get('text_raw')
            pic_infos = item.get('pic_infos')

            if pic_infos:
                # # 给图片创建对应微博的文件夹
                if not os.path.exists(f"{self.directory}\\{formatted_name}"):
                    os.mkdir(f"{self.directory}\\{formatted_name}")
                # 解析图片的url
                pic_name_list = []
                for pic in pic_infos:
                    url = pic_infos[pic]['original']['url']
                    pic_name_list.append(f"{formatted_name}\\{url.split('/')[-1]}")
                    self.get_image(url, formatted_name)
                context.append([formatted_time, text_raw, pic_name_list])

            else:
                pic_name_list = []
                # print(formatted_time, text_raw, sep='\n')
                context.append([formatted_time, text_raw, pic_name_list])

        return context

    def get_image(self, url, formatted_name):
        resp = self.client.get(url, headers=self.headers, cookies=self.cookies)
        pic_name = url.split('/')[-1]
        with open(f'{self.directory}\\{formatted_name}\\{pic_name}', 'wb') as f:
            f.write(resp.content)

    def run(self):
        self.get_json()
        context_dict = self.parse_json()
        return context_dict

